/*
 * Class: Server
 * Version: 1.00
 * Date: 13 April 2011
 */
package com.pokeoffice.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.pokeoffice.logs.Log;

/**
 * The Class Server.
 *
 * @author Kyle Davis
 * @version 1.00
 * 
 * This is the application's server.It listens on port 2340 for
 * connections from the client. It accepts Commands and executes them
 * by using a CommandQueue
 * 
 * TODO Exception Handling/Recovering, Respond to Client
 */
public class Server implements Runnable {

	/** The port that this server listens on. */
	private static final int PORT = 2340;

	/** The server. */
	private ServerSocket server = null;

	/** The mediator. */
	private Mediator mediator = null;

	/** The shutdown. */
	private boolean shutdown;

	/**
	 * Creates the Server.
	 */
	public Server() {
		Log.write(Log.SERV, "CREATING SERVER");
		mediator = Mediator.get();
		shutdown = false;
	}

	/**
	 * Connects to port PORT and listens for commands to accept from the client.
	 * Commands are placed on a CommandQueue when received
	 */
	public void run() {
		Log.write(Log.SERV, this + "Listening");
		try {
			Log.write(Log.SERV, this + "Opening ServerSocket on port " + PORT);
			server = new ServerSocket(PORT);
		} catch (IOException ioe) {
			Log.write(Log.SERV, this + "Could not listen on port " + PORT);
			Log.write(Log.ERR, ioe.getMessage());
			System.exit(-1);
		}

		while (!shutdown) {
			Socket clientSocket = null;

			try {
				Log.write(Log.SERV, this + "Accepting client socket");
				clientSocket = server.accept();
			} catch (IOException ioe) {
				Log.write(Log.SERV, this
						+ "Failed when accepting client socket");
				Log.write(Log.ERR, ioe.getMessage());
				ioe.printStackTrace();
			}

			Log.write(Log.SERV, this + "Sending to Router");
			mediator.putClient(clientSocket);
		}
	}

	/**
	 * Shutdown the server.
	 */
	public synchronized void shutdown() {
		// FIXME
	}

	/**
	 * A string representation of Server.
	 *
	 * @return "Server"
	 */
	public String toString() {
		return "Server: ";
	}
}
